package com.stlm2.interceptor;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.stlm2.dems.dao.ConfigDao;
import com.stlm2.dems.entity.Config;
import com.stlm2.dems.maintain.entity.Maintain;
import com.stlm2.dems.maintain.service.MaintainService;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


/**
 * Author：fuchunyu
 * Date：2017/7/27
 * Description：
 */
public class TimeInterceptor extends HandlerInterceptorAdapter {
    // 继承HandlerInterceptorAdapter类
    @Resource
    private ConfigDao configDao;
    @Resource
    private MaintainService maintainService;

    private String configName; //配置的参数名
    private String switch_on;  //配置的参数值

    private String outsideOfficeHoursPage;  //配置的升级页面

    /**
     * Author：fuchunyu
     * Date：2017/7/27
     * Description：重写 preHandle()方法，在业务处理器处理请求之前对该请求进行拦截处理
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        Config config=new Config();
        config.setConfigName(configName);
        config=configDao.selectOneFromRedis(config);
        if(config==null){
            config=configDao.getByName(configName);
            List<String> list = new ArrayList<String>();
            list.add("configName");
            configDao.addIntoRedis(config,list);
        }
        if(config.getConfigValue().equals(switch_on)){
            Maintain maintain=maintainService.getLastVersion();
            long beginTime=maintain.getBeginTime().getTime();
            long endTime=maintain.getEndTime().getTime();
            long nowTime=new Date().getTime();
            if(beginTime<=nowTime&&nowTime<=endTime){
                response.sendRedirect(outsideOfficeHoursPage); // 返回提示页面
                return false;
            }
        }
        return true;
    }

    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object o, ModelAndView mav)
            throws Exception {
    }

    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object o, Exception excptn)
            throws Exception {
    }

    public String getSwitch_on() {
        return switch_on;
    }

    public void setSwitch_on(String switch_on) {
        this.switch_on = switch_on;
    }

    public String getConfigName() {
        return configName;
    }

    public void setConfigName(String configName) {
        this.configName = configName;
    }

    public String getOutsideOfficeHoursPage() {
        return outsideOfficeHoursPage;
    }

    public void setOutsideOfficeHoursPage(String outsideOfficeHoursPage) {
        this.outsideOfficeHoursPage = outsideOfficeHoursPage;
    }

}
